﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Collections.Generic;

namespace LotteryAdmin.Controls
{
    public class AutoFillDataGrid : DataGrid
    {
        public static readonly DependencyProperty WidthWeightProperty = DependencyProperty.RegisterAttached(
            "WidthWeight", typeof(int), typeof(AutoFillDataGrid), new PropertyMetadata(0));
        private double paddingRight = 0;

        public AutoFillDataGrid()
        {
            this.SizeChanged += new SizeChangedEventHandler(AutoFillDataGrid_SizeChanged);

        }

        void AutoFillDataGrid_SizeChanged(object sender, SizeChangedEventArgs e)
        {
            int weight = 0;
            double fix = 0;
            int temp = 0;
            Queue<DataGridColumn> queue = new Queue<DataGridColumn>();

            foreach (DataGridColumn column in this.Columns)
            {
                temp = (int)column.GetValue(WidthWeightProperty);
                if (temp > 0)
                {
                    weight += temp;
                    queue.Enqueue(column);
                }
                else
                {
                    fix += column.ActualWidth;
                }
            }

            double width = e.NewSize.Width - this.paddingRight - fix - this.Padding.Left - this.Padding.Right;
            double actualWidth = 0;
            
            while (queue.Count > 0)
            {
                DataGridColumn column = queue.Dequeue();
                temp = (int)column.GetValue(WidthWeightProperty);
                actualWidth = width * (double)temp / weight;
                if (actualWidth < column.MinWidth)
                {
                    actualWidth = column.MinWidth;
                }
                if (actualWidth > column.MaxWidth)
                {
                    actualWidth = column.MaxWidth;
                }
                column.Width = new DataGridLength(actualWidth);

            }
        }

        public double PaddingRight
        {
            get
            {
                return this.paddingRight;
            }
            set
            {
                this.paddingRight = value;
            }
        }

        public static void SetWidthWeight(DataGridColumn column, int value)
        {
            column.SetValue(WidthWeightProperty, value);
        }

        public static int GetWidthWeight(DataGridColumn column)
        {
            return (int)column.GetValue(WidthWeightProperty);
        }
    }
}
